<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}角色`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="drawerProps.row!.roleName" placeholder="请填写角色名" clearable></el-input>
      </el-form-item>
      <el-form-item label="权限字符" prop="roleStr">
        <el-input v-model="drawerProps.row!.roleStr" placeholder="请填写权限字符" clearable></el-input>
      </el-form-item>
      <el-form-item label="权限列表" prop="permissions">
        <el-checkbox-group v-model="drawerProps.row!.permissions">
          <el-checkbox :label="permission.id" v-for="permission in permissionList" :key="permission.id">
            {{ permission.permissionName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="菜单" prop="menus">
        <el-checkbox-group v-model="drawerProps.row!.routes">
          <el-checkbox :label="menus.id" v-for="menus in menuList" :key="menus.id">
            {{ menus.meta.title }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RoleDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Role } from "@/api/interface";
import { getPermissionListApi } from "@/api/modules/permission";
import { getMenuList } from "@/api/modules/menu";
import { useAuthStore } from "@/stores/modules/auth";

const permissionList = ref<Permission[]>([]);
const getPermissionList = async () => {
  try {
    const { data } = await getPermissionListApi(); // 替换成实际的 API 调用
    permissionList.value = data;
  } catch (error) {
    console.error("Error fetching permission list:", error);
  }
};

const menuList = ref<Menu.MenuOptions[]>([]);
const getMenus = async () => {
  try {
    const { data } = await getMenuList({ component: null, path: null, title: null });
    console.log(data.list);
    menuList.value = data.list;
  } catch (error) {
    console.error("Error fetching permission list:", error);
  }
};

const rules = reactive({
  roleName: [{ required: true, message: "请填写角色姓名" }],
  roleStr: [{ required: true, message: "请填写权限字符" }]
});

interface Permission {
  id: number;
  permissionName: string;
}

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Role.ResRoleList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  getPermissionList();
  getMenus();
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const authStore = useAuthStore();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}角色成功！` });
      // 刷新菜单
      await authStore.getAuthMenuList();
      // 刷新按钮
      await authStore.getAuthButtonList();
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
